import matplotlib.pyplot as plt
import matplotlib.tri as mtri
import numpy as np
import cv2

np.random.seed(1234)

# 生成2D空间随机点
N = 100
idx = list(range(N))
xs = np.random.randint(1, 98, N).tolist()
ys = np.random.randint(1, 98, N).tolist()

plt.scatter(xs, ys)
plt.show()

# 同opencv建立三角剖分
subdiv = cv2.Subdiv2D((0, 0, 100, 100)) # 提供坐标范围，用于构建超级三角形
for x, y in zip(xs, ys):
    subdiv.insert((xs, ys)) # 逐个插入平面上的点
tri_cv2 = subdiv.getTriangleList() # 得到剖分结果

# 绘制三角剖分结果的数据准备
XS, YS, IS = [], [], []
for n in range(len(tri_cv2)):
    t = tri_cv2[n]  # t 包含了三角形的顶点坐标
    XS.extend([t[0], t[2], t[4]])   # 3个顶点X坐标
    YS.extend([t[1], t[3], t[6]])   # 3个顶点的Y坐标
    IS.append((n*3, n*3+1, n*3+2))  # 面对应得顶点序号
    
# 显示
fig, ax = plt.subplots()
ax.triplot(mtri.Triangulation(XS, YS, IS), 'k-')
plt.show()
    